<?php
namespace App\Http\Controllers;

use App\Tool\Error;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    //当前客户端所在省份
    public $province = '';
    public $province_code;
    //当前客户端所在城市名称
    public $city = '';
    public $city_code = '';
    //当前IP
    public $IP;
    //淘宝IP库
    public $taobaoAddress = 'http://ip.taobao.com/service/getIpInfo.php';

    public function __construct(Request $request)
    {
        $this->IP = $request->getClientIp();
//        $this->IP = '36.47.165.139';
        $this->getIpAddress();
    }
    /**
     * 根据公网IP地址获取对应城市
     */
    public function getIpAddress(){
        //淘宝IP库
        $ip_res = @file_get_contents($this->taobaoAddress."?ip=$this->IP");
        $ip_res = json_decode($ip_res,true);
        if($ip_res['code'] == 0){
            $this->province = $ip_res['data']['region'];
            $this->city = $ip_res['data']['city'];
            $map[] = ['name','like','%'.$this->city.'%'];
            $map[] = ['level', 2];
            $city_code = DB::table('area')->where($map)->select(['code','parentId'])->first();
            $this->province_code = $city_code->parentId;
            $this->city_code = $city_code->code;
            return $city_code;
        }
        return false;
    }


    /**
     * 返回错误
     * @param $errorCode
     * @param null $errorMsg
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($errorCode, $errorMsg = null)
    {
        if ($errorMsg === null) {
            $errorMsg = empty(Error::MSG[$errorCode]) ? '未定义错误 ' . $errorCode : Error::MSG[$errorCode];
        }
        $result = array(
            'code' => $errorCode,
            'msg' => $errorMsg
        );
        return response()->json($result);
    }

    /**
     * 返回成功
     * @param $message
     * @param null $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($message = '操作成功', $data = null, $start = null, $end = null)
    {
        $res = array(
            'code' => 0,
            'msg' => $message,
        );
        if (isset($data)) {
            $res['data'] = $data;
        }
        if (isset($start)) {
            $res['start'] = $start;
        }
        if (isset($end)) {
            $res['end'] = $end;
        }
        return response()->json($res);
    }
}

